﻿using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Xml;
using System.Data;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.System;
using System.Web.Services.Protocols;
using System.Web.Script.Services;

namespace Jumpton.SFA.Service
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service : System.Web.Services.WebService
    {
       
        #region Property
        public Authentication SessionHeader
        {
            get;
            set;
        }
        #endregion

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Password">密码</param>
        /// <param name="IMEI">设备识别码</param>
        /// <param name="IMSI">手机号码识别码</param>
        /// <returns></returns>
        [WebMethod]
        [System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public String Login(LoginUser user)
        {
           //验证license是否有效
            LoginResult result = new LoginResult();
            try
            {
                result = new FormAuthorization().Authorization(user, Context);
                if (result != null && result.LoginSuccessful)
                {
                    //修改为自动获取当前的虚拟目录路径
                    string path = null;
                    try
                    {
                        path = Context.Request.Url.ToString().Substring(0, Context.Request.Url.ToString().ToLower().LastIndexOf("/") + 1);
                    }
                    catch { }

                    String[] values = new VersionPublishManager().GetLastestVersion(result.DomainID, result.Organization, result.UserID, user.PlatformCode, user.VersionCode);
                    //检查最新版本
                    if (values != null && values.Length > 0)
                    {
                        result.CabFile = path + "APP/" + values[1];
                        result.Version = values[0];
                    }

                    result.ServerTime = DateTime.Now.ToString("yyyyMMddHHmmss");
                    Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(Jumpton.SFA.Server.BusinessRule.System.LogType.LOGIN_SUCCESS, result.UserName, result.UserID, "登录成功");
                    
                }
            }
            catch (Exception ex)
            {
                if (result != null)
                    result.Message = ex.StackTrace;
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(Jumpton.SFA.Server.BusinessRule.System.LogType.LOGIN_FAILURE, result.UserName, result.UserID, "移动终端登录 - 异常:" + ex.Message);
            }
            var js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return js.Serialize(result);
           

        }

      

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        [SoapHeader("SessionHeader", Direction = SoapHeaderDirection.In)]
        [WebMethod]
        public Boolean ChangePassword(decimal userid, string NewPassword)
        {
            //if (SessionHeader == null)
            //    throw new Exception("非法访问");
            //string userid = null;

            //if (!string.IsNullOrEmpty(SessionHeader.SessionID))
            //{
            //    //判断该Session是否有效
            //    userid = new SessionManager().IsExpire(SessionHeader.SessionID);
            //}
            bool Successful = false;
            try
            {
                if (new UserManager().ChangePassword(userid, NewPassword))
                {
                    Successful = true;
                }
                //var user = new UserManager().GetUserByID((decimal)userid);
                //if (user != null)
                //{
                //    user.PASSWORD = Jumpton.Common.Functions.EncryptString(NewPassword);
                //    SystemConfigManager configManager = new SystemConfigManager();

                //    SystemConfig config = configManager.Load(ConfigType.LoginNeedToChangePassword);
                //    if (config != null && config.Value.Equals("1"))
                //        user.PASSWORDCHANGED = "1";
                //    user.Save();
                //    //写错误日志
                //    EventManager.CreateNewEvent(LogType.PASSWOD_CHANGED, user.CODE, userid, string.Format("用户{0}修改新密码为:××××", user.LOGINNAME));
                //    Successful = true;
                //    //Jumpton.FSA.BusinessLogic.MasterData.EmployeeManager manager = new Jumpton.FSA.BusinessLogic.MasterData.EmployeeManager();
                //    //manager.UpdateSysLoginDateInfo(user.USERID);
                //}
            }
            catch (Exception err)
            {
               
               // 写错误日志
                Jumpton.SFA.Server.BusinessRule.System.EventManager.CreateNewEvent(LogType.EXCEPTION, userid.ToString(), userid.ToString(), "Message:" + err.Message + ",StackTrace Info：" + err.StackTrace);
            }
            return Successful;
        }

        private Boolean ValidRequest(Object[] values, String Version, String RequestKey)
        {
            String key = Keys.SecurityKey[Version];
            String str = "";
            foreach (Object s in values)
            {
                str += s;
            }
            str += key;
            return Jumpton.Common.Functions.EncryptString(str) == RequestKey;

        }


         /// <summary>
        /// 查找指定范围内的客户
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        [SoapHeader("SessionHeader", Direction = SoapHeaderDirection.In)]
        [System.Web.Script.Services.ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        [WebMethod]
        public String GetCustomrForLBS(decimal DomainID,decimal Latitude, decimal Lontitude, decimal Distance)
        {
            DataResult result = new DataResult();
            if (ValidRequest(new Object[] { DomainID, Latitude, Lontitude, SessionHeader.RequestKey }, SessionHeader.Version, SessionHeader.UniqueKey))
            {
                result.Message = "验证失败";
            }
            String SQL = String.Format(@"select C.NAME,c.CUSTOMER_PRODUCT_LIST_ID as CPL_ID,C.ID,dbo.GetDistance({1},{2},identity2,identity1) as DISTANCE  from CUSTOMERS C where DOMAIN_ID={0}
                and IDENTITY1>0 and dbo.GetDistance({1},{2},identity2,identity1)<={3} ORDER BY DISTANCE", DomainID, Latitude, Lontitude, Distance);
            System.Collections.Generic.List<String> list = new System.Collections.Generic.List<string>();
            IDataReader reader = null;
            try
            {
                reader = Jumpton.Data.SqlData.ExecuteReader(SQL);
                while (reader.Read())
                {
                    list.Add(reader.GetString(0)+ "," + reader.GetValue(1).ToString()+ "," + reader.GetValue(2).ToString()+","+reader.GetValue(3).ToString());
                }
                result.Values = list;
                result.Successful = true;
            }
            catch(Exception err)
            {
                result.Values = null;
                result.Message = err.Message;
                result.Successful = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                    reader = null;
                }
            }
            var js = new System.Web.Script.Serialization.JavaScriptSerializer();
            return js.Serialize(result);
        }
      
    }
}

